import * as React from 'react';
import {useState,useEffect, useCallback} from 'react'
import Box from '@mui/material/Box';
import Container from '@mui/material/Container';

import Filter from '../filter/filter'
import CountriesList from '../CounteriesList/CounteriesList';
import PaginationControlled from '../pagination/pagination';
// import fetchAll from '../../api/all'; 
import useCountriesData from '../../hooks/useCountriesData';


const Home = ({ mode}) =>{
  const { countries, error,  loading,  fetchData } = useCountriesData();
  const [page, setPage] = useState(1);
  const [value, setValue] = useState("");
  const [region, setRegion] = useState("");
  useEffect(() => {
    setPage(1);
  }, [region, value]);
  const filter = useCallback(() => {
    let matchedCountries = countries;
    if (region !== "") {
      matchedCountries = matchedCountries.filter(
        country => country.region === region
      );
    }
    if (value&&value.trim() !== "") {
      matchedCountries = matchedCountries.filter((country) => {
        return (
          country.name.toUpperCase().includes(value.toUpperCase()) ||
          country.region.toUpperCase().startsWith(value.toUpperCase()) ||
          (country.capital
            ? country.capital.toUpperCase().startsWith(value.toUpperCase())
            : false) ||
          country.nativeName.toUpperCase().includes(value.toUpperCase())
        );
      });
    }
    return matchedCountries;
  }, [countries, region, value]);
  return(
    <Box sx={{ p:1 ,  bgcolor: (mode === 'dark' ?  'hsl(207, 26%, 17%)' : 'hsl(0, 1%, 98%)'), flexDirection:"column" } }>
      <Container
        sx={{
          minHeight: '100vh',
          transition: '0.3s',
        }}
      >
      {/* Country filter */}
      <Box m={"1rem 0px"}  >
        <Filter           
          handlerAction={setValue}
          region={region}
          setRegion={setRegion}/>
      </Box>
      
      {/* Country list */}
      <Box m={"1rem 0px"} flexGrow="1" >
        <CountriesList  page={page-1} countries={filter()} refreshAction={fetchData} error={error} loading={loading} /> 
      </Box>
      {/* Pageination */}
      <PaginationControlled totalPages={filter().length } page={page} setPage ={setPage}/> 
    </Container>
  </Box>
  )
}

export default Home;